package com.codefish.framework.spring.beans.factory.config;

import com.codefish.framework.spring.beans.exception.BeansException;
import com.codefish.framework.spring.beans.factory.support.BeanDefinition;
import com.codefish.framework.spring.beans.factory.support.PropertyValue;
import com.codefish.framework.spring.core.utils.ClassUtils;

import java.util.Date;
import java.util.List;

/**
 * 自动填充bean中所有Date类型的'gmtCreated'字段属性值为当前时间
 *
 * @author <a href='https://gitee.com/hzf2281'>codefish</a>
 * @version 1.0.0
 * @since 2022/10/03 下午 02:16
 */
public class AutoFillTimestampConfigurer implements IBeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(IConfigurableListableBeanFactory beanFactory) throws BeansException {
        //获取所有BeanDefinition的name
        List<String> beanDefinitionNames = beanFactory.getBeanDefinitionNames();

        for (String bdName : beanDefinitionNames) {
            //遍历获取所有的beanDefinition
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(bdName);
            Class<?> beanClass;
            if (beanDefinition != null && (beanClass = beanDefinition.getBeanClass()) != null) {
                if (ClassUtils.containField(beanClass, "gmtCreated", Date.class)) {
                    //bd的class符合注入条件，添加PropertyValue
                    beanDefinition.addPropertyValue(new PropertyValue("gmtCreated", new Date()));
                }
            }
        }
    }
}
